package com.example.studentalarm.activity;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.studentalarm.R;
import com.example.studentalarm.adapter.TimetableAdapter;
import com.example.studentalarm.bean.EventBusData;
import com.example.studentalarm.bean.TimetableBean;
import com.example.studentalarm.calendar.DateUtil;
import com.example.studentalarm.calendar.RepayPlanInfo;
import com.example.studentalarm.config.SharedPreferencesUtils;
import com.example.studentalarm.constant.ApiConstant;
import com.example.studentalarm.database.DbManager;
import com.example.studentalarm.database.DbOpenHelper;
import com.example.studentalarm.dialog.CalenDarDialog;
import com.example.studentalarm.presenter.TimetableMvpPresenter;
import com.example.studentalarm.service.AlarmReceiver;
import com.example.studentalarm.service.AlarmService;
import com.example.studentalarm.utils.PermissionManage;
import com.example.studentalarm.utils.TimeUtils;
import com.example.studentalarm.utils.Utils;
import com.example.studentalarm.view.ITimetableView;
import com.example.studentalarm.widget.AppleRefreshView;
import com.example.studentalarm.widget.BaseDialog;
import com.example.studentalarm.widget.SwipeItemLayout;
import com.example.studentalarm.widget.statuslayout.OnRetryListener;
import com.example.studentalarm.widget.statuslayout.StateLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/***
 * 主界面
 */
public class MainActivity extends ListPageModelActivity<ITimetableView, TimetableMvpPresenter> implements ITimetableView {
    @BindView(R.id.tvSet)
    TextView tvSet;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.appleRefreshView)
    AppleRefreshView appleRefreshView;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    private TimetableAdapter adapter;
    private Context mContext;
    private long exitTime = 0;
    private CalenDarDialog calenDarDialog;
    private String selectDate;


    @Override
    public int getLayoutUrl() {
        return R.layout.activity_main;
    }

    @Override
    public StateLayout.Builder getBuilderLayout() {
        return new StateLayout.Builder(this)
                .setStateLayout(R.layout.state_layout)
                .setStateLayoutAlertContent("暂无相关信息")
                .setStateLayoutImageResrouce(R.mipmap.no_info)
                .setStateLayoutViewId(R.id.button_retry)
                .onRetryListener(new OnRetryListener() {
                    @Override
                    public void onRetry() {
                        presenter.requestTimetableBydate(selectDate);
                    }
                });
    }

    @Override
    public void registerById() {
        ButterKnife.bind(this);
        recyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); //垂直listView显示方式
//        new PermissionManage.Builder(this)
//                .setPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE
//                })
//                .builder()
//                .requestPermission();
        appleRefreshView.setRefreshListener(new AppleRefreshView.RefreshListener() {
            @Override
            public void onRefresh() {
                startAlarmService();
                presenter.requestTimetableBydate(selectDate);
            }
        });
    }

    @Override
    public void initData() {
        presenter.attach(this);
        mContext = this;
        EventBus.getDefault().register(this);
        adapter = new TimetableAdapter(this);
        recyclerView.setAdapter(adapter);
        // 默认当前日期
        selectDate = TimeUtils.getDate(TimeUtils.PATTERN);

        tvTitle.setText(TimeUtils.getDate(selectDate));

        adapter.setOnItemClickListener(new TimetableAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                TimetableBean timetableBean = adapter.getmData().get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("id", timetableBean.getId());
                gotoActivity(EditTimetableActivity.class, bundle);
            }

            @Override
            public void deleteTimetable(final TimetableBean bean) {
                BaseDialog baseDialog = new BaseDialog(mContext);
                baseDialog.setTipMessage("确定要删除课程:" + bean.getName() + "吗？");
                baseDialog.show();
                baseDialog.setClickListener(new BaseDialog.ButtonClick() {

                    @Override
                    public void rightClick() {
                        presenter.deleteTimetable(bean.getId());
                        cancelAlarm(mContext, bean.getId());
                        presenter.requestTimetableBydate(selectDate);
                    }

                    @Override
                    public void leftClick() {
                    }
                });
            }
        });
        if (getIntent().getExtras() != null && AlarmReceiver.ACTION_NOTIFICATION_OPENED.equals(getIntent().getAction())) {
            Bundle bundle = getIntent().getExtras();
            Integer id = bundle.getInt("id");
            DbManager.getInstance().updateAlarmState(id, ApiConstant.AlarmState.SEND);//处理重复提醒闹钟
            //取消闹钟
            cancelAlarm(this, id);
            Intent intent = new Intent(this, EditTimetableActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        presenter.requestTimetableBydate(selectDate);
        startAlarmService();
    }

    public void showCalenDarDiaLog() {
        // 初始化日历 默认显示当前日期
        calenDarDialog = new CalenDarDialog(mContext, new CalenDarDialog.InitDataInf() {
            @Override
            public String getSelectDate() {
                return selectDate;
            }

            @Override
            public ArrayList<RepayPlanInfo> getRemindData() {
                return presenter.getCalendarRemindData();
            }
        });

        calenDarDialog.setOnItemClick(new CalenDarDialog.ItemOnClick() {
            @Override
            public void onClick(String date) {
                selectDate = date;
                tvTitle.setText(TimeUtils.getDate(selectDate));
                presenter.requestTimetableBydate(selectDate);
            }
        });
        calenDarDialog.show();
    }

    @Override
    protected TimetableMvpPresenter initPresenter() {
        return new TimetableMvpPresenter(this);
    }

    public void onEvent(EventBusData event) {
        if (event.getWhat() == ApiConstant.EventBus.REFRESH_OK) {
            startAlarmService();
            presenter.requestTimetableBydate(selectDate);
        }
    }

    //取消闹钟
    public void cancelAlarm(Context mContext, Integer alarmId) {
        Intent intent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(mContext, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }

    @OnClick({R.id.tvSet, R.id.tvAdd, R.id.tvTitle})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvSet:
                gotoActivity(SetActivity.class);
                break;
            case R.id.tvAdd:
                gotoActivity(EditTimetableActivity.class);
                break;
            case R.id.tvTitle:
                if (calenDarDialog == null || !calenDarDialog.isShowing()) {
                    showCalenDarDiaLog();
                }
                break;
        }
    }

    @Override
    public void getTimetableList(List<TimetableBean> beanList) {
        appleRefreshView.finishRefresh(true);
        hideRootView(recyclerView);
        adapter.bindDataList(beanList);
        appleRefreshView.finishRefresh(true);
    }

    @Override
    public void showEmptyList(String warn) {
        appleRefreshView.finishRefresh(true);
        showRootView(recyclerView);
        rootView.showEmptyView();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 双击退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(10);
            }
            return true;

        }
        return super.onKeyDown(keyCode, event);
    }
}
